<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chatroom</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #chat { list-style: none; padding: 0; }
        #chat li { padding: 8px; border-bottom: 1px solid #ddd; }
        #message { width: calc(100% - 100px); }
    </style>
</head>
<body>
<h1>WebSocket Chatroom</h1>
<div>
    <input type="text" id="message" placeholder="Type your message here...">
    <button id="send">Send</button>
</div>
<ul id="chat"></ul>

<script>

    let ws = null;

    document.getElementById('send').addEventListener('click', function () {
        const message = document.getElementById('message').value;
        sendMessage(message);
        document.getElementById('message').value = '';
    });

    function sendMessage(message) {
        const userBh = 'user123'; // 假设的userBh，实际应用中需要从后端获取
        const userName = 'Guest'; // 假设的userName，实际应用中需要从后端获取
        const url = `ws://localhost:8090/websocket/connect/${userBh}/${userName}`;

        ws = new WebSocket(url);
        ws.onopen = function (event) {
            ws.send(message);
        };

        ws.onmessage = function (event) {
            const chatList = document.getElementById('chat');
            const li = document.createElement('li');
            li.textContent = event.data;
            chatList.appendChild(li);
        };

        ws.onclose = function (event) {
            console.log('WebSocket connection closed.');
        };

        ws.onerror = function (error) {
            console.error('WebSocket error: ', error);
        };
    }

    window.addEventListener("unload", function () {
        if (ws) {
            ws.close()
        }
    })
</script>
</body>
</html>
